const { RawSource } = require('webpack-sources');
const getBranchVersionInfo = require('./utils/branchInfo.js')

const pluginName = 'WebpackBuildLogs'
class WebpackBuildLogs {
  options;
  branchInfo;
  constructor(options) {
    this.options = options;
    this.branchInfo = getBranchVersionInfo()
  }
  apply(compiler) {
    const { filename, appInfos} = this.options;

    const {
      branchName,
      lastHash,
      commitUser,
      commitDate,
      commitMsg,
      last5Msg,
      buildDate } = this.branchInfo

    const fileContent = `
|名称     |信息        |
|---------|-------------|
|应用名称: | ${appInfos.name}|
|应用版本: | ${appInfos.version}|
|应用分支: | ${branchName}|
|最后提交: | ${lastHash}|
|提交信息: | ${commitMsg}|
|提交时间: | ${commitDate}|
|打包人:   | ${commitUser}|
|打包时间: | ${buildDate}|
`
    const FileName = filename || 'build_version.md'
    compiler.hooks.emit.tap(pluginName, (compilation) => {
      compilation.assets[FileName] = new RawSource(fileContent);
    })
  }
}

module.exports = WebpackBuildLogs;